package com.lyb.ui.lend.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.lyb.R;
import com.lyb.app.App;
import com.lyb.base.BaseFragment;
import com.lyb.base.PermissionsListener;
import com.lyb.config.Constant;
import com.lyb.dialog.ActivityFragmentDialog;
import com.lyb.dialog.AlertFragmentDialog;
import com.lyb.events.AuthenticationRefreshEvent;
import com.lyb.events.FragmentRefreshEvent;
import com.lyb.events.UIBaseEvent;
import com.lyb.ui.authentication.activity.PerfectInformationActivity;
import com.lyb.ui.lend.activity.BankInputPwdActivity;
import com.lyb.ui.lend.activity.LendConfirmLoanActivity;
import com.lyb.ui.lend.adapter.ActivityListAdapter;
import com.lyb.ui.lend.bean.ConfirmLoanBean;
import com.lyb.ui.lend.bean.HomeIndexResponseBean;
import com.lyb.ui.lend.contract.LendContract;
import com.lyb.ui.lend.presenter.LendPresenter;
import com.lyb.ui.main.MainActivity;
import com.lyb.ui.main.WebViewActivity;
import com.lyb.util.CalendarUtil;
import com.lyb.util.SpUtil;
import com.lyb.util.StringUtil;
import com.lyb.util.TimeUtil;
import com.lyb.util.ToastUtil;
import com.lyb.util.Tool;
import com.lyb.widget.DrawableCenterTextView;
import com.lyb.widget.LockableScrollView;
import com.lyb.widget.NumberPickerView;
import com.lyb.widget.RollView;
import com.lyb.widget.loading.LoadingLayout;
import com.lyb.widget.recycler.BaseRecyclerAdapter;
import com.umeng.analytics.MobclickAgent;
import com.yintong.activity.BindBankActivity;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.data.JPushLocalNotification;


/**********
 * 借款 (For flavor 零用宝 )
 */
public class LendFragment extends BaseFragment<LendPresenter> implements OnClickListener, LendContract.View {

    @BindView(R.id.loading_layout)
    LoadingLayout      mLoadingLayout;
    @BindView(R.id.roll_view)
    RollView           mRollView; //滚动消息view
    @BindView(R.id.tv_credit_money)
    TextView           mTvCreditMoney;  //信用额度
    @BindView(R.id.rl_credit)
    RelativeLayout     mRlCredit;  //信用额度布局
    @BindView(R.id.scroll_view)
    LockableScrollView mScrollView; //滚动view
    @BindView(R.id.refresh)
    SwipeRefreshLayout mRefresh;    //刷新view
    @BindView(R.id.ll_loan_content)
    LinearLayout       mLlLoanContent;   //未借款时布局
    @BindView(R.id.tv_money)
    TextView           mTvMoney;  //借款金额
    @BindView(R.id.tv_bigMoney)
    TextView           mTvBigMoney;   //"最大可借"与"可借额度"文字
    //    @BindView(R.id.hsb_selected_money)
    //    HomeSeekBar        mHsbSelectedMoney;  //金额拖动view
    //    @BindView(R.id.rg_days)
    //    RadioGroup         mRgDays; //借款日期容器
    @BindView(R.id.picker_money)
    NumberPickerView   mPickerMoney; //选择金额
    @BindView(R.id.picker_day)
    NumberPickerView   mPickerDay; //选择日期
    @BindView(R.id.ll_verify)
    LinearLayout       mLlVerify; //认证步骤布局
    @BindView(R.id.tv_phone_auth)
    TextView           mTvPhoneAuth;     //显示当前认证多少步骤
    @BindView(R.id.tv_rent_btn)
    TextView           mTvRentBtn;        //登录or借款按钮
    @BindView(R.id.ll_status_content)
    LinearLayout       mLlStatusContent;  //借款后布局
    @BindView(R.id.tv_loan_tag)
    TextView           mTvLoanTag;    //标题
    @BindView(R.id.ll_status_item_view)
    LinearLayout       mLlStatusItemView; //借款状态view
    @BindView(R.id.activity_recycler)
    RecyclerView       mActivityRecycler; //首页活动列表
    @BindView(R.id.ll_service_fee)
    LinearLayout       mLlServiceFee; //登录时查看服务费按钮
    @BindView(R.id.fl_check_service_fee)
    FrameLayout        mFlCheckServiceFee; //未登录时查看服务费按钮
    @BindView(R.id.ll_surplus_status)
    LinearLayout       mLlSurplusStatus;
    @BindView(R.id.tv_surplus_title)
    TextView           mTvSurplusTitle;

    //    @BindView(R.id.banner)
    //    ImageView mBanner; //广告位
    @BindView(R.id.banners)
    Banner mBanner;

    @BindView(R.id.view_message)
    View mViewMessageLine;

    @BindView(R.id.credit_text_divider)
    View mCreditTextLine;

    @BindView(R.id.tv_surplus_txt)
    TextView mTvSurplusTxt;

    @BindView(R.id.tv_surplus_day)
    TextView               mTvSurplusDay;
    @BindView(R.id.tv_surplus_btn)
    DrawableCenterTextView mTvSurplusBtn;
    @BindView(R.id.tv_credit_inquiry)
    TextView               mCreditText;
    @BindView(R.id.tv_account_manager)
    TextView               mAccountManager;
    @BindView(R.id.tv_interest_money)
    TextView               mInterestText;
    @BindView(R.id.tv_arrival_amount)
    TextView               mArrivalAmountText;
    public static LendFragment                   lendFragment;
    private       HomeIndexResponseBean.ItemBean bean;
    private       int                            maxMoney, loanMoney;
    private int                                      loanDay;
    private double                                   realMoney;
    private int                                      realMaxMoney;
    private double                                   serviceMoney;
    private int                                      intoMoney; //还款金额
    private String                                   loanEndTime; //还款时间
    private int                                      surplusDay; //剩余还款天数
    private int                                      nextLoanDay; //剩余可借款时间倒计时
    private HomeIndexResponseBean.AmountDaysListBean moneyPeriodBean;
    private List<HomeIndexResponseBean.IndexImagesBean> mActivityListBean = new ArrayList<>();

    private ActivityListAdapter mActivityListAdapter;

    private MainActivity mainActivity;
    private List<Integer> defaultBanner = new ArrayList<>();

    public static LendFragment getInstance() {
        if (lendFragment == null) {
            lendFragment = new LendFragment();
        }
        return lendFragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_lend_main;
    }

    @Override
    public void initPresenter() {
        mPresenter.init(this);
    }

    @Override
    public void loadData() {
        mainActivity = (MainActivity) mActivity;
        EventBus.getDefault().register(this);
        initView();
        initListener();
    }

    private void initView() {
        //硬件加速状态下无法显示虚线
        mViewMessageLine.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mCreditTextLine.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        mTitle.setTitle(false, App.getAPPName());
        mTitle.setRightTitle(R.mipmap.icon_message, new OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = App.getConfig().ACTIVITY_CENTER;
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
            }
        });

        mRefresh.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.theme_color));
        mActivityRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        mActivityRecycler.setFocusable(false);
        mActivityListAdapter = new ActivityListAdapter();
        mActivityRecycler.setAdapter(mActivityListAdapter);
        mActivityListAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(mActivity, WebViewActivity.class);
                intent.putExtra("url", mActivityListAdapter.getData().get(position).getReUrl());
                startActivity(intent);
            }
        });
        mBanner.setImageLoader(new GlideImageLoader());
        mBanner.setDelayTime(5000);
        //加载数据
        mLoadingLayout.setStatus(LoadingLayout.Loading);
        mPresenter.loadIndex(false);

        if (App.getConfig().getLoginStatus()) {
            mLlServiceFee.setVisibility(View.VISIBLE);
            mFlCheckServiceFee.setVisibility(View.GONE);
            mTvRentBtn.setText("我要借款");
        } else {
            mLlServiceFee.setVisibility(View.GONE);
            mFlCheckServiceFee.setVisibility(View.VISIBLE);
            mTvRentBtn.setText("马上登录");
        }
    }


    @Override
    public void indexSuccess(HomeIndexResponseBean result, boolean isClickLend) {
        mLoadingLayout.setStatus(LoadingLayout.Success);
        bean = result.getItem();
        //banner
        if (result.getBanners() != null && result.getBanners().size() > 0) {
            mBanner.update(result.getBanners());
        } else {
            //default banners
            defaultBanner.clear();
            defaultBanner.add(R.mipmap.lend_status_canlend_banner);
            defaultBanner.add(R.mipmap.lend_status_repapyment_banner);
            mBanner.update(defaultBanner);
        }
        //点击借款获取最新的认证状态 并且只有在indexSuccess()获取数据成功后处理跳转
        if (isClickLend) {
            if (bean.getVerify_loan_pass() == 1) {
                toLoan();
            } else {
                //前置4步认证都完成
                if (bean.getVerify_loan_nums() == bean.getAll_auth_Count() - 1 && bean.getAuth_bank() ==
                        0) {
                    //跳转绑卡页面
                    BindBankActivity.goBindBank(getContext());
                    ToastUtil.show("请绑定银行卡");
                } else {
                    Intent liftingQuotaIntent = new Intent(getActivity(), PerfectInformationActivity.class);
                    startActivityToLogin(liftingQuotaIntent);
                }
            }
        }
        //金额集合
        List<Integer> amounts = result.getAmount_days_list().getAmounts();
        if (amounts != null && amounts.size() > 2) {
            //需求：只能借整百
            //如果最后一个值与倒数第二位相等或者最后一个值除100不等于0，则去除最后一个值
            if (amounts.get(amounts.size() - 1).equals(amounts.get(amounts.size() - 2)) || amounts.get(amounts.size()
                    - 1) % 10000 != 0) {
                amounts.remove(amounts.size() - 1);
            }
            //获取最大金额值
            realMaxMoney = amounts.get(amounts.size() - 1);
            mTvMoney.setText(realMaxMoney / 100 + "");
        }
        if (amounts != null && amounts.size() == 1) {
            //获取最大金额值
            realMaxMoney = amounts.get(amounts.size() - 1);
            mTvMoney.setText(realMaxMoney / 100 + "");
        }
        loanMoney = amounts.get(amounts.size() - 1) / 100;
        loanDay = result.getAmount_days_list().getDays().get(0);
        //金额集合
        moneyPeriodBean = result.getAmount_days_list();
        calculateRate(moneyPeriodBean.getDays());
        // 借款滚动信息
        mRollView.setContent(result.getUser_loan_log_list());
        //动态加载借款时间
        setDays(result.getAmount_days_list().getDays());
        //热门活动集合
        mActivityListBean = result.getIndex_images();
        mActivityListAdapter.clearData();
        mActivityListAdapter.addData(mActivityListBean);
        //获取数据后进行显示在界面上
        setData(isClickLend);

    }

    @Override
    public void toLoanSuccess(ConfirmLoanBean result) {
        Intent intent = new Intent(getActivity(), LendConfirmLoanActivity.class);
        intent.putExtra(BankInputPwdActivity.TAG_OPERATE_BEAN, result);
        startActivity(intent);
    }

    @Override
    public void confirmFailedSuccess() {
        mPresenter.loadIndex(false);
        EventBus.getDefault().post(new FragmentRefreshEvent(UIBaseEvent.EVENT_LOAN_FAILED));
    }

    @Override
    public void TipsAlert(String content, String url) {

    }

    @Override
    public void showLoading(String content) {
        if (bean != null) {
            App.loadingContent(mActivity, content);
        }
    }

    @Override
    public void stopLoading() {
        App.hideLoading();
        if (mRefresh.isRefreshing()) {
            mRefresh.setRefreshing(false);
        }
    }

    /**
     * @param msg
     *         请求异常信息
     * @param type
     *         若有多个请求，用于区分不同请求（不同请求失败或有不同的处理）
     */
    @Override
    public void showErrorMsg(String msg, String type) {
        if (TextUtils.isEmpty(type)) {
            return;
        }
        if (type.equals(mPresenter.TYPE_INDEX)) {//首页接口
            ToastUtil.showToast(msg);
            loadingStatusView(msg);
        } else if (type.equals(mPresenter.TYPE_FAILED)) { //借款失败调用
            mPresenter.loadIndex(false);
        } else if (type.equals(mPresenter.TYPE_LOAN)) {   //验证借款信息
            ToastUtil.showToast(msg);
        }
    }

    //为view设置数据
    private void setData(boolean isClickLend) {
        if (bean != null) {
            //认证状态
            if (bean.getVerify_loan_pass() == 1) {//已认证
                mLlVerify.setVisibility(View.GONE);
                mRlCredit.setVisibility(View.VISIBLE);
                mTvCreditMoney.setText("" + bean.getCard_amount() / 100);
                mTvBigMoney.setText("可借额度");
            } else {
                mRlCredit.setVisibility(View.GONE);
                mTvBigMoney.setText("最高借款额度");
                if (bean.getVerify_loan_nums() > 0) {
                    mLlVerify.setVisibility(View.VISIBLE);
                } else if (bean.getVerify_loan_nums() == 0) {
                    mLlVerify.setVisibility(View.GONE);
                }
                mTvPhoneAuth.setText("您已" + bean.getCard_verify_step() + ",完成认证即可拿钱，加油！");
            }

            //借款状态  bean.getLoan_infos()不为空时为已登录并借款
            if (bean.getLoan_infos() != null) {
                showView(mLlStatusContent);
                setLoanStatus();
            } else {// 没有借款
                nextLoanDay = bean.getNext_loan_day();
                if (nextLoanDay > 0 && App.getConfig().getLoginStatus()) {
                    String countDownTag = SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN);
                    if (TextUtils.isEmpty(countDownTag) || !countDownTag.equals(Constant.CACHE_TAG_NEXT_LOAN)) {
                        SpUtil.putString(Constant.CACHE_TAG_COUNT_DOWN, Constant.CACHE_TAG_NEXT_LOAN);
                    }
                    showView(mLlSurplusStatus);
                } else {
                    showView(mLlLoanContent);
                    if (!isClickLend) {
                        if (moneyPeriodBean != null) {
                            List<Integer> amounts = moneyPeriodBean.getAmounts();
                            if (amounts != null && amounts.size() >= 2) {
                                maxMoney = (amounts.size() - 1) * 100;
                            } else {
                                maxMoney = 0;
                            }
                        }
                        mPickerMoney.setSelection(0);
                        if (moneyPeriodBean != null && moneyPeriodBean.getAmounts() != null) {
                            List<String> showMoneys = new ArrayList<>();
                            for (Integer moneyItem : moneyPeriodBean.getAmounts()) {
                                showMoneys.add(moneyItem / 100 + "");
                            }
                            mPickerMoney.setSelector(showMoneys.toArray());
                            int end = moneyPeriodBean.getAmounts().size() - 1;
                            mPickerMoney.smoothScrollTo(end);
                        }

                        //初始化默认的贷款天数
                        mPickerDay.setSelection(0);
                        if (moneyPeriodBean != null && moneyPeriodBean.getDays() != null) {
                            mPickerDay.smoothScrollTo(0);
                            loanDay = moneyPeriodBean.getDays().get(0);
                        }
                        if (moneyPeriodBean != null && moneyPeriodBean.getDays() != null) {
                            calculateRate(moneyPeriodBean.getDays());
                        }
                    }
                }

            }
        }
    }

    //审核状态改变
    private void setLoanStatus() {
        mLlStatusItemView.removeAllViews();
        HomeIndexResponseBean.ItemBean.LoanInfosBean loaninfo = bean.getLoan_infos();
        mTvLoanTag.setText(loaninfo.getHeader_tip());
        List<HomeIndexResponseBean.ItemBean.LoanInfosBean.ListsBean> loans = loaninfo.getLists();
        if (loans != null && loans.size() > 0) {
            for (int i = 0; i < loans.size(); i++) {
                HomeIndexResponseBean.ItemBean.LoanInfosBean.ListsBean loan = loans.get(i);
                if (i == 0) {
                    addLoanStatusView(loan, R.layout.layout_loan_status_item1, i);
                } else if (i == loans.size() - 1) {
                    addLoanStatusView(loan, R.layout.layout_loan_status_item3, i);
                } else {
                    addLoanStatusView(loan, R.layout.layout_loan_status_item2, i);
                }
            }
        }
        HomeIndexResponseBean.ItemBean.LoanInfosBean.ButtonBean button = loaninfo.getButton();
        if (button != null) {
            final String orderId = button.getId();
            View btnLayout = LayoutInflater.from(getActivity()).inflate(R.layout.layout_loan_status_button, null);
            TextView tv_ikonw_btn = (TextView) btnLayout.findViewById(R.id.tv_ikonw_btn);
            tv_ikonw_btn.setText(button.getMsg());
            tv_ikonw_btn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPresenter.confirmFailed(orderId);
                }
            });
            mLlStatusItemView.addView(btnLayout);
        }
        intoMoney = loaninfo.getIntoMoney();//还款金额
        loanEndTime = loaninfo.getLoanEndTime();//还款日期 格式:2016-12-12
        surplusDay = loaninfo.getLastRepaymentD();//还款倒计时天数
        if (intoMoney > 0 && !TextUtils.isEmpty(loanEndTime)) {//满足这个条件,表示当前为还款阶段
            //通知还款页面列表刷新
            EventBus.getDefault().post(new FragmentRefreshEvent(UIBaseEvent.EVENT_BORROW_MONEY_SUCCESS));

            if (!TextUtils.isEmpty(SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN)) &&
                    SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN).equals(Constant.CACHE_TAG_REPAY_COUNT_DOWN)) {
                showView(mLlSurplusStatus);
            } else {
                //切换倒计时页面
                View btnLayout = LayoutInflater.from(getActivity()).inflate(R.layout.layout_loan_status_button, null);
                TextView tv_ikonw_btn = (TextView) btnLayout.findViewById(R.id.tv_ikonw_btn);
                tv_ikonw_btn.setText("我知道了");
                tv_ikonw_btn.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SpUtil.putString(Constant.CACHE_TAG_COUNT_DOWN, Constant.CACHE_TAG_REPAY_COUNT_DOWN);
                        showView(mLlSurplusStatus);
                    }
                });
                mLlStatusItemView.addView(btnLayout);
            }

            showCalenderDialog();
        }
    }

    /**
     * 切换 未借款、借款中。倒计时布局
     * @param view
     */
    private void showView(View view) {
        switch (view.getId()) {
            case R.id.ll_loan_content:
                mLlLoanContent.setVisibility(View.VISIBLE);
                mLlStatusContent.setVisibility(View.GONE);
                mLlSurplusStatus.setVisibility(View.GONE);
                //                mBanner.setImageResource(R.mipmap.lend_status_canlend_banner);
                break;
            case R.id.ll_status_content:
                mLlLoanContent.setVisibility(View.GONE);
                mLlStatusContent.setVisibility(View.VISIBLE);
                mLlSurplusStatus.setVisibility(View.GONE);
                //                mBanner.setImageResource(R.mipmap.lend_status_canlend_banner);
                break;
            case R.id.ll_surplus_status:
                mLlLoanContent.setVisibility(View.GONE);
                mLlStatusContent.setVisibility(View.GONE);
                mLlSurplusStatus.setVisibility(View.VISIBLE);
                //                mBanner.setImageResource(R.mipmap.lend_status_repapyment_banner);
                if (SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN).equals(Constant.CACHE_TAG_REPAY_COUNT_DOWN)) {
                    String days = String.valueOf(Math.abs(surplusDay)).length() == 1 ? (surplusDay == 0 ?
                            String.valueOf(surplusDay) : "0" + Math.abs(surplusDay)) : String.valueOf(Math.abs
                            (surplusDay));
                    if (surplusDay < 0) {
                        mTvSurplusTxt.setText("逾 期");
                        mTvSurplusTitle.setText("本次已逾期时间");
                        //                        pushDateMessage("您已经逾期 " + days + " 天，请及时还款哦！");
                    } else {
                        mTvSurplusTxt.setText("还 剩");
                        mTvSurplusTitle.setText("距离本次还款时间");
                        //                        pushDateMessage("距离本次还款还剩 " + days + " 天。");
                    }
                    mTvSurplusBtn.setText("现在就还");
                    mTvSurplusBtn.setEnabled(true);
                    mTvSurplusBtn.setGravity(Gravity.CENTER);
                    mTvSurplusBtn.setCompoundDrawablePadding(0);
                    mTvSurplusBtn.setCompoundDrawables(null, null, null, null);
                    mTvSurplusDay.setText(String.valueOf(Math.abs(surplusDay)).length() == 1 ? (surplusDay == 0 ?
                            String.valueOf(surplusDay) : "0" + Math.abs(surplusDay)) : String.valueOf(Math.abs
                            (surplusDay)));
                } else if (SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN).equals(Constant.CACHE_TAG_NEXT_LOAN)) {
                    mTvSurplusTitle.setText("距离下次申请借款时间");
                    mTvSurplusTxt.setText("还 剩");
                    String nowLoanDate = TimeUtil.getCurrentDateByOffset("yyyy-MM-dd 00:00:00", Calendar
                            .DAY_OF_MONTH, nextLoanDay);
                    if (TextUtils.isEmpty(SpUtil.getString(Constant.CACHE_CALENDAR_LOAN_DATE)) ||
                            !SpUtil.getString(Constant.CACHE_CALENDAR_LOAN_DATE).equals(nowLoanDate)) {
                        mTvSurplusBtn.setText("提醒我");
                        mTvSurplusBtn.setEnabled(true);
                    } else {
                        mTvSurplusBtn.setText("已添加提醒");
                        mTvSurplusBtn.setEnabled(false);
                    }
                    mTvSurplusBtn.setGravity(Gravity.CENTER_VERTICAL);
                    Drawable left = ContextCompat.getDrawable(mActivity, R.mipmap.remind);
                    left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
                    mTvSurplusBtn.setCompoundDrawables(left, null, null, null);
                    mTvSurplusBtn.setCompoundDrawablePadding(Tool.dip2px(mContext, 5));
                    mTvSurplusDay.setText(String.valueOf(nextLoanDay).length() == 1 ? (nextLoanDay == 0 ? String
                            .valueOf(nextLoanDay) : "0" + nextLoanDay) : String.valueOf(nextLoanDay));

                    if(bean != null && !StringUtil.isBlank(bean.getTg_img()) && !StringUtil.isBlank(bean.getTg_url())){
                        ActivityFragmentDialog.newInstance(bean.getTg_img(), bean.getTg_url())
                                .show(getFragmentManager(), ActivityFragmentDialog.TAG);
                    }
                }
                break;
        }
    }

    //发送一条本地通知 还剩多少天还款或已逾期多少天
    private void pushDateMessage(String content) {

        JPushLocalNotification msg = new JPushLocalNotification();
        msg.setBuilderId(0);
        //        msg.setTitle("Look Here");
        msg.setContent(content);
        msg.setNotificationId(11111111);
        msg.setBroadcastTime(System.currentTimeMillis() + 1000 * 2);

        //        Map<String, Object> map = new HashMap<String, Object>();
        //        map.put("name", "jpush test");
        //        map.put("test", "666");
        //        JSONObject json = new JSONObject(map);
        //        msg.setExtras(json.toString());
        JPushInterface.addLocalNotification(App.getContext(), msg);
    }

    private AlertFragmentDialog dialog;

    /**
     * 日历功能
     */
    private void showCalenderDialog() {
        String calendarPermissions = SpUtil.getString(Constant.CACHE_CALENDAR_PERMISSIONS);
        boolean permissions = ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_CALENDAR) ==
                PackageManager.PERMISSION_DENIED;
        //未授权则弹出框
        if (TextUtils.isEmpty(calendarPermissions) && permissions) {
            if (dialog == null) {
                dialog = new AlertFragmentDialog.Builder(mActivity).setLeftBtnText("不允许")
                        .setLeftCallBack(new AlertFragmentDialog.LeftClickCallBack() {
                            @Override
                            public void dialogLeftBtnClick() {
                                SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "no");
                            }
                        })
                        .setRightBtnText("允许")
                        .setContent("开启日历还款提醒，不再忘记还钱，更快提升额度。")
                        .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                            @Override
                            public void dialogRightBtnClick() {
                                requestPermissions(new String[]{Manifest.permission.WRITE_CALENDAR}, new
                                        PermissionsListener() {
                                            @Override
                                            public void onGranted() {
                                                insetCalender();
                                            }

                                            @Override
                                            public void onDenied(List<String> deniedPermissions, boolean isNeverAsk) {
                                                SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "no");
                                            }
                                        });
                            }
                        }).build();
            } else if (!dialog.getShowsDialog()) {
                dialog.show(getChildFragmentManager(), AlertFragmentDialog.TAG);
            }
        } else if ("yes".equals(calendarPermissions) || !permissions) {
            insetCalender();
        }
    }

    private void insetCalender() {
        //往日历中插数据
        final String mLoanEndTime = SpUtil.getString(Constant.CACHE_CALENDAR_REPAY_DATE);//获取缓存的还款日期
        int mLoanEndMoney = SpUtil.getInt(Constant.CACHE_CALENDAR_REPAY_MONEY); //获取缓存的还款金额
        if (TextUtils.isEmpty(mLoanEndTime) || !mLoanEndTime.equals(loanEndTime) ||
                mLoanEndMoney != intoMoney) {//缓存的日期为空或者与返回的日期不相等，则去日历插入
            mActivity.requestPermissions(new String[]{Manifest.permission.WRITE_CALENDAR}, new PermissionsListener() {
                @Override
                public void onGranted() {
                    SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "yes");
                    CalendarUtil.deleteCalendarEvent(mContext, App.getAPPName());
                    String refundDate = loanEndTime;//还款日期 2017-01-06格式
                    String refundAmount = String.valueOf(intoMoney);//还款金额
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                    String time = refundDate + " 00:00:00";
                    Date date = null;
                    long mFinalTime = 0;
                    try {
                        date = format.parse(time);
                        long dateTime = date.getTime();
                        mFinalTime = dateTime - 14 * 60 * 60 * 1000;//还款日的前一天10:00提示
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    String fomater = CalendarUtil.dateFomater(refundDate);
                    if (CalendarUtil.addCalendarEvent(getContext(),
                            App.getAPPName(), "明天" + fomater + ", " + App.getAPPName() + " 需还款" + refundAmount + "元" +
                                    "(如已提前还款请忽略)",
                            mFinalTime)) {
                        SpUtil.putString(Constant.CACHE_CALENDAR_REPAY_DATE, loanEndTime);
                        SpUtil.putInt(Constant.CACHE_CALENDAR_REPAY_MONEY, intoMoney);
                    }
                }

                @Override
                public void onDenied(List<String> deniedPermissions, boolean isNeverAsk) {
                    SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "no");
                    ToastUtil.showToast("日历提醒已被禁止,如有需要,请手动开启");
                }
            });
        }
    }

    /**
     * 加载借款时状态布局
     * @param loan
     * @param layout
     */
    private void addLoanStatusView(HomeIndexResponseBean.ItemBean.LoanInfosBean.ListsBean loan, int layout, int
            position) {
        View content = LayoutInflater.from(getActivity()).inflate(layout, null);
        ImageView item_icon = (ImageView) content.findViewById(R.id.item_icon);
        View item_line = content.findViewById(R.id.item_line);
        if (position == 0 || position == 1) {
            item_line.setBackgroundResource(R.mipmap.icon_dashed);
        }
        TextView tv_title = (TextView) content.findViewById(R.id.tv_title);
        TextView tv_info = (TextView) content.findViewById(R.id.tv_info);
        tv_title.setText(Html.fromHtml(loan.getTitle()));
        tv_info.setText(loan.getBody());
        if (loan.getTag() == 0) {
            item_icon.setImageResource(R.mipmap.icon_loan_status_passed);
            tv_title.setTextColor(ContextCompat.getColor(mContext, R.color.global_label_color));
            tv_info.setTextColor(ContextCompat.getColor(mContext, R.color.global_label_color));
        } else if (loan.getTag() == 1) {
            item_icon.setImageResource(R.mipmap.state_underway);
            tv_title.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
            tv_info.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
        } else if (loan.getTag() == 2) {
            item_icon.setImageResource(R.mipmap.icon_loan_status_nopassed);
            tv_title.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
            tv_info.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
        } else if (loan.getTag() == 3) {
            item_icon.setImageResource(R.mipmap.state_done);
            tv_title.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
            tv_info.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
        }
        mLlStatusItemView.addView(content);
    }

    private void loadingStatusView(String message) {
        if ("网络不可用".equals(message)) {
            mLoadingLayout.setStatus(LoadingLayout.No_Network);
        } else {
            mLoadingLayout.setErrorText(message)
                    .setStatus(LoadingLayout.Error);
        }
        mLoadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mPresenter.loadIndex(false);
            }
        });
    }

    private void initListener() {

        //选择金钱的seekBar
        //        mHsbSelectedMoney.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        //            /**
        //             * 拖动条进度改变的时候调用
        //             */
        //            @Override
        //            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        //                if (moneyPeriodBean == null) {
        //                    return;
        //                }
        //                int position = (progress + 50) / 100;
        //                if (position >= moneyPeriodBean.getAmounts().size()) {
        //                    position = moneyPeriodBean.getAmounts().size() - 1;
        //                }
        //                loanMoney = moneyPeriodBean.getAmounts().get(position) / 100;
        //                //下面到账金额的改变
        //                calculateRate(moneyPeriodBean.getDays());
        //                //字体的改变
        //                mTvMoney.setText(loanMoney + "");
        //            }
        //
        //            /**
        //             * 开始拖动条进度的时候调用
        //             */
        //            @Override
        //            public void onStartTrackingTouch(SeekBar seekBar) {
        //                mRefresh.setEnabled(false);//拖动时禁止刷新
        //            }
        //
        //            /**
        //             * 结束拖动条进度的时候调用
        //             */
        //            @Override
        //            public void onStopTrackingTouch(SeekBar seekBar) {
        //                mRefresh.setEnabled(true);//拖动结束解锁刷新
        //                mHsbSelectedMoney.setProgress((mHsbSelectedMoney.getProgress() + 50) / 100 * 100);
        //            }
        //        });

        mPickerMoney.setListener(new NumberPickerView.OnValueChanged() {
            @Override
            public void onValueChanged(int position) {
                if (moneyPeriodBean == null || moneyPeriodBean.getAmounts() == null || moneyPeriodBean.getDays() ==
                        null) {
                    return;
                }
                if (position < 0 || position > moneyPeriodBean.getAmounts().size() - 1) {
                    return;
                }
                //                loanMoney = moneyPeriodBean.getAmounts().get(position) / 100;

                // 转为整数金额 21000 -> 20000
                loanMoney = (int) (Math.floor(moneyPeriodBean.getAmounts().get(position) / 10000) * 100);
                if (moneyPeriodBean.getAmounts().get(position) / 100 == 10) {
                    // 10元 仅供测试
                    loanMoney = moneyPeriodBean.getAmounts().get(position) / 100;
                }

                //下面到账金额的改变
                calculateRate(moneyPeriodBean.getDays());
                //字体的改变
                mTvMoney.setText(loanMoney + "");
            }
        });

        mPickerDay.setListener(new NumberPickerView.OnValueChanged() {
            @Override
            public void onValueChanged(int position) {
                if (moneyPeriodBean == null || moneyPeriodBean.getAmounts() == null || moneyPeriodBean.getDays() ==
                        null) {
                    return;
                }
                if (position < 0 || position > moneyPeriodBean.getDays().size() - 1) {
                    return;
                }
                loanDay = moneyPeriodBean.getDays().get(position);
                calculateRate(moneyPeriodBean.getDays());
            }
        });

        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.loadIndex(false);
            }
        });
    }

    @OnClick({R.id.tv_improveMoney, R.id.tv_rent_btn, R.id.tv_phone_auth, R.id.fl_check_service_fee, R.id
            .tv_surplus_btn})
    public void onClick(View v) {
        if (Tool.isFastDoubleClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.tv_improveMoney://提额链接跳转
//                Intent intent = new Intent(getActivity(), WebViewActivity.class);
//                intent.putExtra("title", "注册");
//                intent.putExtra("improveUrl", Constant.LIMIT_URL);
//                startActivity(intent);
                startActivity(PerfectInformationActivity.class);
                break;
            case R.id.tv_rent_btn:  //借款按钮
                if (!App.getConfig().getLoginStatus()) {
                    App.toLogin(getActivity());
                } else {
                    mPresenter.loadIndex(true);
                    //                    if (bean.getVerify_loan_pass() == 1) {
                    //                        toLoan();
                    //                    } else {
                    //                        //前置4步认证都完成
                    //                        if (bean.getVerify_loan_nums() == bean.getAll_auth_Count() - 1 && bean
                    // .getAuth_bank() ==
                    //                                0) {
                    //                            //跳转绑卡页面
                    //                            BindBankActivity.goBindBank(getContext());
                    //                            ToastUtil.show("请绑定银行卡");
                    //                        } else {
                    //                            Intent liftingQuotaIntent = new Intent(getActivity(),
                    // PerfectInformationActivity.class);
                    //                            startActivityToLogin(liftingQuotaIntent);
                    //                        }
                    //                    }
                }
                break;
            case R.id.tv_phone_auth:    //步骤认证
                Intent liftingQuotaIntent = new Intent(getActivity(), PerfectInformationActivity.class);
                startActivityToLogin(liftingQuotaIntent);
                break;
            case R.id.fl_check_service_fee: //未登录时查看服务费
                App.toLogin(getActivity());
                break;
            //            case R.id.ll_service_fee_check: //登录后查看服务费
            //                CostDetailsDialog.newInstance(loanMoney+"",loanDay+"").show(getChildFragmentManager(),
            // CostDetailsDialog.TAG);
            //                break;
            case R.id.tv_surplus_btn:
                String status = SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN);
                if (TextUtils.isEmpty(status)) {
                    return;
                }
                if (status.contains(Constant.CACHE_TAG_REPAY_COUNT_DOWN)) {//还款倒计时
                    if (App.getConfig().getLoginStatus()) {
                        mainActivity.getGroup().check(R.id.rb_rent_lend);
                    } else {
                        App.toLogin(mActivity);
                        return;
                    }
                } else if (status.contains(Constant.CACHE_TAG_NEXT_LOAN)) {//下次可借款倒计时
                    //往日历中插数据
                    final String mLoanStartTime = SpUtil.getString(Constant.CACHE_CALENDAR_LOAN_DATE);//获取缓存的下次可借款日期
                    Log.e("----", "mLoanStartTime=" + mLoanStartTime + "loanEndTime =" + loanEndTime);
                    if (TextUtils.isEmpty(mLoanStartTime) || !mLoanStartTime.equals(loanEndTime))
                    {//缓存的日期为空或者与返回的日期不相等，则去日历插入
                        mActivity.requestPermissions(new String[]{Manifest.permission.WRITE_CALENDAR}, new
                                PermissionsListener() {
                                    @Override
                                    public void onGranted() {
                                        CalendarUtil.deleteCalendarEvent(mContext, App.getAPPName());
                                        //下次可借款日期 格式:yyyy-MM-dd 00:00:00
                                        String refundDate = TimeUtil.getCurrentDateByOffset("yyyy-MM-dd 00:00:00",
                                                Calendar
                                                        .DAY_OF_MONTH, nextLoanDay);

                                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                                        Date date;
                                        long mFinalTime = 0;
                                        try {
                                            date = format.parse(refundDate);
                                            long dateTime = date.getTime();
                                            mFinalTime = dateTime + 10 * 60 * 60 * 1000;//可借款日的当天10:00提示
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                        if (CalendarUtil.addCalendarEvent(getContext(),
                                                App.getAPPName(), "今天" + App.getAPPName() + "可以申请借款啦",
                                                mFinalTime)) {
                                            SpUtil.putString(Constant.CACHE_CALENDAR_LOAN_DATE, refundDate);
                                            mTvSurplusBtn.setEnabled(false);
                                            mTvSurplusBtn.setText("已添加提醒");
                                        }
                                    }

                                    @Override
                                    public void onDenied(List<String> deniedPermissions, boolean isNeverAsk) {
                                        SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "no");
                                        if (isNeverAsk) {
                                            mActivity.toAppSettings("日历权限已被禁止", false);
                                        }
                                    }
                                });
                    }
                }
                break;
            default:
                break;
        }
    }

    private void setDays(final List<Integer> days) {
        if (days == null || days.isEmpty()) {
            return;
        }
        List<String> showDays = new ArrayList<>();
        for (Integer day : days) {
            showDays.add(day + "天");
        }

        mPickerDay.setSelector(showDays.toArray());

        //        mPickerDay.setDisplayedValues(showDays.toArray(new String[]{}));
        //        mPickerDay.setMinValue(0);
        //        mPickerDay.setMaxValue(showDays.size() - 1);
        //        mPickerDay.setValue(0);
        //        mPickerDay.setWrapSelectorWheel(false);
        //        if (days == null || days.isEmpty()) {
        //            return;
        //        }
        ////        if (mRgDays.getChildCount() > 0) {
        ////            mRgDays.removeAllViews();
        ////        }
        //        int margin = Tool.dip2px(mContext, 25);
        //        for (int i = 0; i < days.size(); i++) {
        //            RadioButton btn = new RadioButton(mContext);
        //            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(0, Tool.dip2px(mContext, 40), 1);
        //            if (i > 0) {
        //                params.leftMargin = margin;
        //            }
        //            btn.setLayoutParams(params);
        //            btn.setText(days.get(i) + "天");
        //            btn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        //            btn.setTextAppearance(mContext, R.style.homeDayTextColor);
        //            btn.setGravity(Gravity.CENTER);
        //            //4.4和以下系统去除radioButton样式
        //            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
        //                try {
        //                    Field field = btn.getClass().getSuperclass().getDeclaredField("mButtonDrawable");
        //                    field.setAccessible(true);
        //                    field.set(btn, null);
        //                } catch (Exception e) {
        //                    e.printStackTrace();
        //                }
        //            } else {
        //                btn.setButtonDrawable(null);
        //            }
        //            btn.setBackgroundResource(R.drawable.selector_home_time_btn);
        //            mRgDays.addView(btn);
        //        }
        //        mRgDays.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        //            @Override
        //            public void onCheckedChanged(RadioGroup group, int checkedId) {
        //                for (int i = 0; i < group.getChildCount(); i++) {
        //                    if (group.getChildAt(i).getId() == checkedId) {
        //                        loanDay = days.get(i);
        //                        calculateRate(days);
        //                        break;
        //                    }
        //                }
        //            }
        //        });
        //        if (loanDay == 0) {
        //            mRgDays.check(mRgDays.getChildAt(days.size() - 1).getId());
        //        } else {
        //            for (int i = 0; i < days.size(); i++) {
        //                if (days.get(i) == loanDay) {
        //                    mRgDays.check(mRgDays.getChildAt(i).getId());
        //                    break;
        //                }
        //            }
        //        }
    }

    /**
     * 当天数选择的时候，计算费用
     */
    private void calculateRate(List<Integer> amountDaysList) {

        if (loanMoney == 0) {
            mCreditText.setText("0.00元");
            mAccountManager.setText("0.00元");
            mInterestText.setText("0.00元");
            mArrivalAmountText.setText("0.00元");
        } else {
            List<Double> interests = moneyPeriodBean.getInterests();
            if (amountDaysList.size() != interests.size()) {
                return;
            }
            if (moneyPeriodBean.getDaysList() == null || moneyPeriodBean.getDaysList().size() == 0) {
                return;
            }
            if (Tool.isBlank(moneyPeriodBean.getDaysList().get(0).getCreditVet() + "")) {//因为后台分登陆和未登录状态导致该判断必须要；
                return;
            }
            for (int i = 0; i < interests.size(); i++) {
                if (loanDay == amountDaysList.get(i)) {
                    double creditVet = moneyPeriodBean.getDaysList().get(i).getCreditVet() / 100;
                    double accountManage = moneyPeriodBean.getDaysList().get(i).getAccountManage() / 100;
                    double accrual = moneyPeriodBean.getDaysList().get(i).getAccrual() / 100;
                    double maxInterests = (moneyPeriodBean.getDaysList().get(i).getCreditVet() + moneyPeriodBean
                            .getDaysList().get(i).getAccountManage()
                            + moneyPeriodBean.getDaysList().get(i).getAccrual()) / 100;
                    double offset = loanMoney * 100 / (double) realMaxMoney;
                    double creditVetMoney = creditVet * offset;
                    double accountManageMoney = accountManage * offset;
                    double accrualMoney = accrual * offset;
                    double real = loanMoney - creditVetMoney - accountManageMoney - accrualMoney;
                    mCreditText.setText(new DecimalFormat("0.00").format(creditVetMoney) + "元");
                    mAccountManager.setText(new DecimalFormat("0.00").format(accountManageMoney) + "元");
                    mInterestText.setText(new DecimalFormat("0.00").format(accrualMoney) + "元");
                    mArrivalAmountText.setText(new DecimalFormat("0.00").format(loanMoney) + "元");
                    break;
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FragmentRefreshEvent event) {
        //当借款申请成功、还款或续期成功、银行卡绑定或修改成功、登录成、退出功时刷新数据
        if (event.getType() == UIBaseEvent.EVENT_LOAN_SUCCESS ||
                event.getType() == UIBaseEvent.EVENT_LOGIN ||
                event.getType() == UIBaseEvent.EVENT_REPAY_SUCCESS ||
                event.getType() == UIBaseEvent.EVENT_REFRESH_LENDLISY ||
                event.getType() == UIBaseEvent.EVENT_BANK_CARD_SUCCESS ||
                event.getType() == UIBaseEvent.EVENT_LOGOUT) {
            // 数据刷新
            mPresenter.loadIndex(false);
            if (App.getConfig().getLoginStatus()) {
                mLlServiceFee.setVisibility(View.VISIBLE);
                mFlCheckServiceFee.setVisibility(View.GONE);
                mTvRentBtn.setText("我要借款");
            } else {
                mLlServiceFee.setVisibility(View.GONE);
                mFlCheckServiceFee.setVisibility(View.VISIBLE);
                mTvRentBtn.setText("马上登录");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAuthenticationRefresh(AuthenticationRefreshEvent event) {
        // 认证成功 数据刷新
        mPresenter.loadIndex(false);
    }

    private void toLoan() {
        if (loanMoney <= 0) {
            ToastUtil.showToast("借款额度为0,暂不可借款");
            mPresenter.loadIndex(false);
            return;
        }
        if (loanDay <= 0) {
            ToastUtil.showToast("借款期限错误");
            return;
        }
        if (loanMoney > (bean.getCard_amount() / 100)) {
            ToastUtil.showToast("您的最高可借额度仅为" + bean.getCard_amount() / 100 + "哦");
            return;
        }
        mPresenter.toLoan(String.valueOf(loanMoney), String.valueOf(loanDay));
    }

    @Override
    public void onResume() {
        super.onResume();
        mRollView.play();
        mBanner.startAutoPlay();
        MobclickAgent.onPageStart("首页"); //统计页面，"MainScreen"为页面名称，可自定义
        MobclickAgent.onEvent(getContext(), "lend");
    }


    @Override
    public void onPause() {
        super.onPause();
        mRollView.onStop();
        mBanner.stopAutoPlay();
        MobclickAgent.onPageEnd("首页");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        lendFragment = null;
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            if (context == null  || imageView == null) {
                return;
            }
            if (Util.isOnMainThread() && !Tool.isActivityDestroyed(mainActivity)) {
                Glide.with(context)
                        .load(path)
                        .placeholder(R.mipmap.banner_loading)
                        .error(R.mipmap.banner_error)
                        .into(imageView);
            }
        }
    }
}